<?php
/**
 * S3
 * 
 * @author ShuangYa
 * @package Blog
 * @category Addon
 * @link http://www.sylingd.com/
 * @copyright Copyright (c) 2015 ShuangYa
 * @license http://lab.sylingd.com/go.php?name=blog&type=license
 */

use \blog\libs\Common;

class S3_Attachment {
	protected $config;
	protected $sdk;
	
	public function __construct($connect = TRUE) {
		$this->config = unserialize(Common::option('attachmentS3'));
		if (!class_exists('S3SimpleSdk')) {
			$root = str_replace('\\', '/', __DIR__ ) . '/';
			require($root . 's3-simple-sdk.php');
		}
		if ($connect) {
			$this->sdk = new S3SimpleSdk($this->config);
		}
	}
	/**
	 * 获取From
	 * @return array
	 */
	public function getForm() {
		return [
			// ['show' => '直接上传', 'name' => 'use_presigned_url', 'type' => 'checkbox', 'checked' => ($this->config['use_presigned_url'] == 1 ? TRUE : FALSE), 'val' => 1],
			['show' => 'AccessKeyId', 'name' => 'access_key_id', 'type' => 'text', 'val' => $this->config['access_key_id']],
			['show' => 'SecretAccessKey', 'name' => 'secret_access_key', 'type' => 'text', 'val' => $this->config['secret_access_key']],
			['show' => 'Endpoint', 'name' => 'endpoint', 'type' => 'text', 'val' => $this->config['endpoint']],
			['show' => 'version', 'name' => 'version', 'type' => 'text', 'val' => $this->config['version']],
			['show' => '地域', 'name' => 'region', 'type' => 'text', 'val' => $this->config['region']],
			['show' => 'Bucket', 'name' => 'bucket', 'type' => 'text', 'val' => $this->config['bucket']]
		];
	}
	/**
	 * 设置
	 * @access public
	 */
	public function config($config) {
		Common::option('attachmentS3', serialize($config));
	}
	/**
	 * 删除
	 * @access public
	 * @param string $path 路径
	 * @return boolean
	 */
	public function delete($path) {
		return $this->sdk->deleteObject($path);
	}
	/**
	 * 上传
	 * @access public
	 * @param string $local 本地文件
	 * @param string $remote 远程路径
	 * @return boolean
	 */
	public function upload($local, $remote) {
		return $this->sdk->putObject($local, $remote);
	}
	
	/**
	 * 是否支持预签名URL
	 */
	public function isPresignedUrl() {
		return $this->config['use_presigned_url'] == 1;
	}
	/**
	 * 生成预签名URL
	 * @access public
	 * @param string $path 路径
	 * @param int $expires 过期时间(秒)
	 * @return string
	 */
	public function getPresignedUrl($path, $expires = 3600) {
		return $this->sdk->createPresignedUrl($path, $expires);
	}
}